package com.ssy.lingxi.system.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.system.dto.response.MiddlegroundUserLoginResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
* 获取登录用户信息工具类
* @author wrc
* @date 2020/5/22
*/
@Component
public class UserDetailsUtil {

    @Resource
    StringRedisTemplate stringRedisTemplate;


    /**
    * 获取已登录用户详情
    * @author wrc，modified by 万宁
    * @date 2020/5/22
    */
    public MiddlegroundUserLoginResponse getLoginUserDetails(HttpServletRequest request){
        String token = request.getHeader("token");
        if(null==token||token.isEmpty()){
            throw new BusinessException(ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE);
        }
        String middlegroundUserLoginResponseJson = stringRedisTemplate.opsForValue().get(token);
        if(middlegroundUserLoginResponseJson == null) {
            throw new BusinessException(ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE);
        }

        MiddlegroundUserLoginResponse middlegroundUserLoginResponse = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            middlegroundUserLoginResponse = mapper.readValue(middlegroundUserLoginResponseJson,MiddlegroundUserLoginResponse.class);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE);
        }

        return middlegroundUserLoginResponse;
    }
}
